<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      >
<head th:replace="fragments/tabhead::headc">
</head>

<body>
<th:block layout:fragment="content">
<!-- 头部 -->
<div style="margin-top:20px">
  <form class="layui-form" id="headForm">
  <input type="hidden" id="bomId" name="id" th:value="${bom.id}"/>
  <div class="layui-form-item layui-elem-quote">
    
   <div class="layui-inline">
      <label class="layui-form-label" style="width:150px">子件编码或名称</label>
      <div class="layui-input-inline" style="width:120px">
        <input name="codeOrName" class="layui-input"/>
      </div>
    </div>
     <div class="layui-inline">
      <label class="layui-form-label" style="width:100px">版本号</label>
      <div class="layui-input-inline" style="width:100px">
        <input name="version" class="layui-input"/>
      </div>
    </div>
	
    <div class="layui-inline" style="float:right;">
      <div class="layui-input-inline" style="width:60px;">
        <button class="layui-btn" id="searchBtn" type="button">查询</button>
      </div>
      <div class="layui-input-inline" style="width:60px;" th:if="${bom.reviewStatus==false}">
     	<button class="layui-btn" id="saveBtn" type="button" authcode="900258">保存</button>
      </div>
      <div class="layui-input-inline" style="width:60px;" th:if="${bom.reviewStatus==false}">
     	<button class="layui-btn layui-btn-danger" id="removeBtn" type="button" authcode="900261">删除</button>
      </div>
      
    </div>
    
  </div>
 </form>
</div>

<div  style="overflow-x:auto;">
<!-- BOM子件信息 -->
 <form  class="layui-form" action="" id="contentForm" lay-filter="contentForm"></form>
</div>
<script>
var materialDialogIdx,bomDialogIdx,trobj,currbomtr;
$(function(){
	layui.use(['form','layer','laytpl'], function(){
		var form = layui.form;
		 //获取原来的添加的数据
		var formData = $("#headForm").serializeJson();
		$.detailLoad("/eng/bom/bomdetails?bomId="+$("#bomId").val(),formData,function(data){
			$("#contentForm").html(data);
			$("#contentTab tbody").append($("#blankTpl tr").parent().html());
			form.render();
		});
		
		//物料获得焦点时弹出对话框选择物料 (必须要有生产属性)
		$("#contentForm").on("focus","input[name='materialCode']",function(){
			trobj = $(this).parents("tr");
			$.post('/eng/bom/selectmaterials', {}, function(str){
				materialDialogIdx=layer.open({
									id:"materialWin",
									title:"子件选择",
								    type: 1,
								    maxmin :true,
								    area: ['1000px', '600px'],
								    content: str,//注意，如果str是object，那么需要字符拼接。
								    zIndex:10
							  });
			});
		});
		
		//BOM版本切换
		$("#contentForm").on("focus","input[name='materialBomVersion']",function(data){
			
			currbomtr = $(this).parents("tr");
			var materialInfoId = currbomtr.find("input[name='materialInfoId']").val();
			var version = currbomtr.find("input[name='materialBomVersion']").val();
			if(materialInfoId=="" || materialInfoId==null){
				return;
			}
			$.post('/eng/bom/bomchange', {}, function(str){
				bomDialogIdx=layer.open({
								id:"BomVersionWin",
								title:"子件选择",
							    type: 1,
							    maxmin :true,
							    area: ['1000px', '600px'],
							    content: str,//注意，如果str是object，那么需要字符拼接。
							    zIndex:10
						  });
			});
		});
		
		//查询按钮点击
		$("#searchBtn").click(function(){
			var data = $("#headForm").serializeJson();
			$("#contentForm").load("/eng/bom/bomdetails?bomId="+data.id,data,function(data){
				$("#contentTab tbody").append($("#blankTpl tr").parent().html());
				form.render();
			});
		});
		//BOM子件保存
		 form.on('submit(contentForm)', function(data){
			 	var data = {};
				data["bomId"]=$("#bomId").val();
				data["companyId"]=$("#companyId").val();
				data["materialBomId"]=$("#materialBomId").val();
				data["attritionRate"] = $("#attritionRate").val();
				data["remark"] = $("#remark").val();
				var items = [];
				var $trs = $("#contentTab tbody tr");
				for(var i=0;i<$trs.size();i++){
					var $tr = $trs.eq(i);
					var id = $tr.find("input[name='id']").val();
					var material_id= $tr.find("input[name='materialInfoId']").val();
					//分子
				    var numeratorDosage = $tr.find("input[name='numeratorDosage']").val();
					//分母
				    var denominatorDosage = $tr.find("input[name='denominatorDosage']").val();
					//需用数量
				    var requirementDosage =  $tr.find("input[name='requirementDosage']").val();
					//生产数量
				    var productionDosage =  $tr.find("input[name='productionDosage']").val();
					//损耗率
				    var attritionRate =  $tr.find("input[name='attritionRate']").val();
					//备注
				    var remark =  $tr.find("input[name='remark']").val();
					//子件BOMID
				    var materialBomId =  $tr.find("input[name='materialBomId']").val();
				    var companyId =  $tr.find("input[name='companyId']").val();
					
				    if(material_id!=''&&numeratorDosage!=''&&denominatorDosage!=''
				    				&&requirementDosage!=''&&productionDosage!=''){
					    items.push({
					    	id:id,
					    	materialInfoId:material_id,
					    	attritionRate:attritionRate,
					    	remark:remark,
					    	materialBomId:materialBomId,
					    	numeratorDosage:numeratorDosage,
					    	denominatorDosage:denominatorDosage,
					    	requirementDosage:requirementDosage,
					    	productionDosage:productionDosage,
					    	
					    });
				    }else{
				    	if(i==$trs.size()-1){
				    		continue;
				    	}
				    	if(material_id==''){
				    		layer.msg("数据第"+(i+1)+"行物料没有选择");
				    	}else if(numeratorDosage=''){
				    		layer.msg("数据第"+(i+1)+"行分子数量没有填写");
				    	}else if(denominatorDosage=''){
				    		layer.msg("数据第"+(i+1)+"行分母数量没有填写")
				    	}else if(requirementDosage==''){
				    		layer.msg("数据第"+(i+1)+"行需用数量没有填写")
				    	}else if(productionDosage==''){
				    		layer.msg("数据第"+(i+1)+"行生产数量没有填写")
				    	}
				    	return false;
				    }
				}
				data["items"] = items;
				$.ajax({url:"/eng/bom/edit-bomitem",
						data:JSON.stringify(data),
						type:"post",
						contentType:"application/json",
						success:function(data){
							if(data.code==200){
								layer.msg("数据保存成功！");
							}else{
								layer.msg(data.message);
							}
						}});
			return false;
		 });
		 
		//保存按钮事件
		$("#saveBtn").click(function(){
			$("#contentForm").submit();
		});
		
		//删除按钮事件
		$("#removeBtn").click(function(){
			//获取所有的checkbox
			var checkedBox = $("#contentTab").find('tbody input[type="checkbox"]:checked');
			var removeids = [];//删除的id数组
			checkedBox.each(function(index, item){
				   var id = $(item).parents('tr').find("input[name='id']").val();
				   if(id!=null&&id!=''){
					   //获取所有的id列表
					   removeids.push(id);
				   }
		           $(item).parents("tr").remove();
		         
		     }); 
			if(removeids.length==0){
				return ;
			}
			var data = {};
			data['ids'] = removeids;
			$.ajax({
	             type: "post",
	             url: "/eng/bom/bomitem-remove",
	             data: JSON.stringify(data),
	             type:"post",
				 contentType:"application/json",
	             success: function(data){
	             	if(data.code==200){
	             		layer.msg(data.message)
	             	}else{
	             		layer.msg(data.message)
	             	}
	             }
			});
		});
		
		//复选框表头操作
		form.on("checkbox(headCheckBox)",function(data){
			 var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');  
	            child.each(function(index, item){  
	              item.checked = data.elem.checked;  
	            });  
	            form.render('checkbox'); 
		});
		
	});
	//分子用量
	$("body").on("blur","#contentTab input[name='numeratorDosage']",function(){
		console.log("numeratorDosage")
		var $tr = $(this).parent().parent();
		//分母用量
		var denominatorDosage = $tr.find("input[name='denominatorDosage']").val();
		//损耗率
		var attritionRate = $tr.find("input[name='attritionRate']").val();
		//setTaxinfo(当前行DOM，分子用量，分母用量，损耗率)
		setTaxinfo($tr,$(this).val(),denominatorDosage,attritionRate);
	}).on("blur","#contentTab input[name='denominatorDosage']",function(){
		var $parent = $(this).parent().parent();
		var $tr = $(this).parent().parent();
		//分子用量
		var numeratorDosage = $tr.find("input[name='numeratorDosage']").val();
		//损耗率
		var attritionRate = $tr.find("input[name='attritionRate']").val();
		setTaxinfo($parent,numeratorDosage,$(this).val(),attritionRate);
	}).on("blur","#contentTab input[name='attritionRate']",function(){
		var $parent = $(this).parent().parent();
		var $tr = $(this).parent().parent();
		//分子用量
		var numeratorDosage = $tr.find("input[name='numeratorDosage']").val();
		//分母用量
		var denominatorDosage = $tr.find("input[name='denominatorDosage']").val();
		setTaxinfo($parent,numeratorDosage,denominatorDosage,$(this).val());
	});
	
	//setTaxinfo(当前行DOM，分子用量，分母用量，损耗率)
	//公式计算函数
	function setTaxinfo($tr,fz,fm,sh){
		if(fz&&fm&&sh){
			//需用数量=分子/分母
			var hynum = fz/fm;
			//生产数量 = 需用数量*(1+损耗率/100)
			var shl = sh/100;
			var scnum = hynum*(1+shl);
			console.log(hynum+"***"+shl+"**"+scnum)
			var _hynum = parseFloat(hynum).toFixed(2);
			var _scnum = parseFloat(scnum).toFixed(2);
			$tr.find("input[name='requirementDosage']").val(_hynum)
				.end().find("input[name='productionDosage']").val(_scnum);
		}
	}
});

</script>
</th:block>
</body>
</html>